using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdminDto.CarType.AreaDtos;
using AvalonAdminDto.CarType.BrandDtos;
using AvalonAdminDto.CarType.CountryDtos;
using AvalonAdminDto.CarType.VehicleSeriesDtos;
using AvalonAdminDto.Common;
using D.UtilCore.Dtos;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;

namespace AvalonAdmin.Pages.CarType.ViewModels.VehicleSeries
{
    /// <summary>
    /// 车系修改视图模型
    /// </summary>
    public class VehicleSeriesModifyViewModel : BaseModifyViewModel
    {
        #region 页面属性及初始化数据
        
        private string? _id;
        public VehicleSeriesModifyViewModel(string? id = null, ViewStatus? viewStatus = ViewStatus.Add) : base()
        {
            _id = id;
            _currentVehicleSeries = new RepVehicleSeries();
            SetupFormStatus(viewStatus);

            InitializeSaleStatusList();

            if (!string.IsNullOrEmpty(id))
            {
                _ = Task.Run(async () => await QueryAsync());
            }
        }

        /// <summary>
        /// 初始化销售状态列表
        /// </summary>
        private void InitializeSaleStatusList()
        {
            SaleStatusList.Clear();
            SaleStatusList.Add(new ComboBoxItem { Text = "在售", Value = 1 });
            SaleStatusList.Add(new ComboBoxItem { Text = "停售", Value = 2 });
            SaleStatusList.Add(new ComboBoxItem { Text = "停产", Value = 3 });
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public override async Task<bool> QueryAsync()
        {
            try
            {
                if (string.IsNullOrEmpty(_id)) return false;

                var response = await HttpHelper<RepVehicleSeries>.GetAsync($"{ApiUrl.GetVehicleSeries}/{_id}");

                if (response?.Code == StatusCodeEnum.OK && response.Data != null)
                {
                    CurrentVehicleSeries = response.Data;

                    // 设置销售状态
                    SelectedSaleStatus = SaleStatusList.FirstOrDefault(x => x.Value == response.Data.SaleStatus);

                    // 加载关联数据
                    await LoadRelatedDataAsync(response.Data);
                }
                else if (response?.Code == StatusCodeEnum.Waring)
                {
                    ShowError(response.Msg);
                }
                else
                {
                    ShowError("服务器异常");
                }
            }
            catch (Exception ex)
            {
                ShowError($"加载数据失败: {ex.Message}");
            }
            return true;
        }

        /// <summary>
        /// 加载关联数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task LoadRelatedDataAsync(RepVehicleSeries data)
        {
            // 加载销售区域信息
            if (!string.IsNullOrEmpty(data.SaleAreaId))
            {
                var areaResponse = await HttpHelper<RepArea>.GetAsync($"{ApiUrl.GetArea}/{data.SaleAreaId}");
                _repArea = areaResponse?.Data;
            }

            // 加载制造国家信息
            if (!string.IsNullOrEmpty(data.ManufacturingCountryId))
            {
                var countryResponse = await HttpHelper<RepCountry>.GetAsync($"{ApiUrl.GetCountry}/{data.ManufacturingCountryId}");
                _repCountry = countryResponse?.Data;
            }

            // 加载品牌信息
            if (!string.IsNullOrEmpty(data.BrandId))
            {
                var brandResponse = await HttpHelper<RepBrand>.GetAsync($"{ApiUrl.GetBrand}/{data.BrandId}");
                _repBrand = brandResponse?.Data;
            }

            // 通知属性更新
            OnPropertyChanged(nameof(SaleArea));
            OnPropertyChanged(nameof(ManufacturingCountry));
            OnPropertyChanged(nameof(Brand));
        }

        #endregion

        #region 数据编辑属性
        private RepArea? _repArea;
        private RepCountry? _repCountry;
        private RepBrand? _repBrand;
        private RepVehicleSeries _currentVehicleSeries;

        /// <summary>
        /// 当前车系
        /// </summary>
        public RepVehicleSeries CurrentVehicleSeries
        {
            get => _currentVehicleSeries;
            set { _currentVehicleSeries = value; OnPropertyChanged(); }
        }

        /// <summary>
        /// 车系名称
        /// </summary>
        public string? Name 
        { 
            get => CurrentVehicleSeries?.Name;
            set 
            { 
                if (CurrentVehicleSeries != null) 
                {
                    CurrentVehicleSeries.Name = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 车系编码
        /// </summary>
        public string? Code 
        { 
            get => CurrentVehicleSeries?.Code;
            set 
            { 
                if (CurrentVehicleSeries != null) 
                {
                    CurrentVehicleSeries.Code = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 英文名称
        /// </summary>
        public string? EnglishName 
        { 
            get => CurrentVehicleSeries?.EnglishName;
            set 
            { 
                if (CurrentVehicleSeries != null) 
                {
                    CurrentVehicleSeries.EnglishName = value;
                    OnPropertyChanged();
                }
            }
        }

        /// <summary>
        /// 销售区域
        /// </summary>
        public string? SaleArea
        {
            get => _repArea?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 制造国家
        /// </summary>
        public string? ManufacturingCountry
        {
            get => _repCountry?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 品牌
        /// </summary>
        public string? Brand
        {
            get => _repBrand?.Name;
            set { OnPropertyChanged(); }
        }

        /// <summary>
        /// 销售状态列表
        /// </summary>
        public ObservableCollection<ComboBoxItem> SaleStatusList { get; set; } = new();

        /// <summary>
        /// 选中的销售状态
        /// </summary>
        public ComboBoxItem? SelectedSaleStatus { get; set; }
        #endregion

        #region 提交，重置

        /// <summary>
        /// 提交
        /// </summary>
        protected override async Task SubmitAsync()
        {
            try
            {
                // 基础数据验证
                if (string.IsNullOrEmpty(Name))
                {
                    ShowWarning("车系名称不能为空");
                    return;
                }

                if (string.IsNullOrEmpty(Code))
                {
                    ShowWarning("车系编码不能为空");
                    return;
                }

                // 构建请求数据
                var requestData = new RepVehicleSeries
                {
                    Id = CurrentVehicleSeries.Id,
                    Name = Name,
                    Code = Code,
                    EnglishName = EnglishName,
                    SaleAreaId = _repArea?.Id,
                    ManufacturingCountryId = _repCountry?.Id,
                    BrandId = _repBrand?.Id,
                    SaleStatus = SelectedSaleStatus?.Value ?? 1
                };

                // 提交数据
                ApiResult<int> res;
                if (string.IsNullOrEmpty(_id))
                {
                    // 新增
                    res = await HttpHelper<int>.PostAsync(ApiUrl.AddVehicleSeries, requestData);
                    HandleApiResponse(res, "添加成功", "添加失败");
                }
                else
                {
                    // 修改
                    res = await HttpHelper<int>.PutAsync(ApiUrl.UpdateVehicleSeries, requestData);
                    HandleApiResponse(res, "修改成功", "修改失败");
                }
               
            }
            catch (Exception ex)
            {
                ShowError($"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            CurrentVehicleSeries = new  RepVehicleSeries();
        } 
        #endregion
    }

    /// <summary>
    /// 下拉框项目
    /// </summary>
    public class ComboBoxItem
    {
        public string Text { get; set; } = string.Empty;
        public int Value { get; set; }
    }
}



